package com.example.administrator.szb.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BasePresenter;
import com.example.administrator.szb.activity.base.MVPBaseActivity;
import com.example.administrator.szb.bean.ResultBean;
import com.example.administrator.szb.bean.Yzm;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.CheckMsgUtils;
import com.example.administrator.szb.util.Contants;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.Toasts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/9/10/010.
 */

public class ForgetPasswordActivity extends MVPBaseActivity {
    @Bind(R.id.forgetpassword_phoneNumber)
    EditText forgetpasswordPhoneNumber;
    @Bind(R.id.forgetpassword_input_yzm)
    EditText forgetpasswordInputYzm;
    @Bind(R.id.forgetpassword_input_password)
    EditText forgetpasswordInputPassword;
    @Bind(R.id.forgetpassword_input_surePassword)
    EditText forgetpasswordInputSurePassword;
    @Bind(R.id.forgetpassword_button_submit)
    Button forgetpasswordButtonSubmit;
    @Bind(R.id.forgetpassword_getYzm)
    TextView forgetpasswordGetYzm;
    @Bind(R.id.bar_title)
    TextView bar_title;
    @Bind(R.id.titleBack)
    LinearLayout forgetpasswordImageview;

    int time = 60;
    private static String yzm_code = "";//验证码用于比对用户输入的验证码
    private ArrayList<String> forgetpassword_info = new ArrayList<String>();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forgetpassword_activity);
        ButterKnife.bind(this);
        SampleApplicationLike.getActivitiesInstance().add(this);
        bar_title.setText("忘记密码");
        forgetpasswordGetYzm.setEnabled(false);
        forgetpasswordGetYzm.setTextColor(Color.parseColor("#ffbcbcbc"));
        forgetpasswordPhoneNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (CheckMsgUtils.isMobileNO(forgetpasswordPhoneNumber.getText().toString().trim())){
                    forgetpasswordGetYzm.setEnabled(true);
                    forgetpasswordGetYzm.setTextColor(getResources().getColor(R.color.basecolor));
                }else {
                    forgetpasswordGetYzm.setEnabled(false);
                    forgetpasswordGetYzm.setTextColor(Color.parseColor("#ffbcbcbc"));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick({R.id.forgetpassword_button_submit, R.id.forgetpassword_getYzm, R.id.titleBack})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.forgetpassword_button_submit:
                submitForgetPassword();
                break;
            case R.id.forgetpassword_getYzm:
                if (!Contants.isMobileNO(forgetpasswordPhoneNumber.getText().toString().trim())){
                    DialogUtil.showToast(this,"手机号格式不正确");
                    return;
                }
                requestYzm();//执行验证获取操作
                break;
            case R.id.titleBack:
                finish();
                break;
        }
    }

    private void submitForgetPassword() {
        //get_info();
        boolean flag = checkInfo();
        if (flag) {
            requestFindPassword();
        }

       // Toasts.show(this, "执行提交", Toast.LENGTH_SHORT);
    }


    /**
     * 执行重置密码的操作
     */
    private void requestFindPassword() {
        Map<String,String> map = new HashMap<String,String>();
        map.put("code", HttpUtil.getParam());
        map.put("tel",forgetpassword_info.get(0));
        map.put("pass",forgetpassword_info.get(2));
        //map.put("type",login_tpye+"");

        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, ResultBean.class, URLAddress.URLBASE+URLAddress.URL_FIND_PASSWORD, map,new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ResultBean login_register = (ResultBean) response;
                if (login_register.getResult() == 1) {
                    Toasts.show(ForgetPasswordActivity.this, "密码重置成功", Toast.LENGTH_SHORT);
                   finish();
                    //DialogUtil.showSimpleDialog(ForgetPasswordActivity.this,"密码重置成功");
                }else{
                    Toasts.show(ForgetPasswordActivity.this, ""+login_register.getErr_msg(), Toast.LENGTH_SHORT);
                   //DialogUtil.showSimpleDialog(ForgetPasswordActivity.this,login_register.getErr_msg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

    public void requestYzm() {
        changeYzmStatu();//改变获取验证码状态
        get_info();
        if(CheckMsgUtils.isMobileNO(forgetpassword_info.get(0))) {
            getYzm();//获取验证码请求
        }

       //get_info();
       // Toasts.show(this, "获取验证码", Toast.LENGTH_SHORT);
    }

    private boolean checkInfo() {
        get_info();
        boolean flag = CheckMsgUtils.isMobileNO(forgetpassword_info.get(0));
        if (!flag) {
            DialogUtil.showSimpleDialog(this,"手机号码格式不正确！");
        }else if(TextUtils.isEmpty(forgetpassword_info.get(1))){
            DialogUtil.showSimpleDialog(this,"请填写验证码");
        }else if(!forgetpassword_info.get(1).equals(yzm_code)){
            DialogUtil.showSimpleDialog(this,"验证码有误！");
        }
        else if(TextUtils.isEmpty(forgetpassword_info.get(2))){
            DialogUtil.showSimpleDialog(this,"请输入密码");
        }else if(!Contants.passIsRight(forgetpassword_info.get(2))){
            DialogUtil.showSimpleDialog(this,"密码必须是6~20位的且有字母或数字的组合");
        }
        else if(TextUtils.isEmpty(forgetpassword_info.get(3))){
            DialogUtil.showSimpleDialog(this,"请输入确认密码");
        }
        else if(!forgetpassword_info.get(2).equals(forgetpassword_info.get(3))){
            DialogUtil.showSimpleDialog(this,"两次输入的密码不一致，请重新输入！");
        }else{
            return true;
        }

        return false;
    }

    private void get_info() {
        forgetpassword_info.clear();
        String phoneNumber = forgetpasswordPhoneNumber.getText().toString().trim();
        String yzm = forgetpasswordInputYzm.getText().toString().trim();
        String password = forgetpasswordInputPassword.getText().toString().trim();
        String surepassword = forgetpasswordInputSurePassword.getText().toString().trim();

        forgetpassword_info.add(phoneNumber);
        forgetpassword_info.add(yzm);
        forgetpassword_info.add(password);
        forgetpassword_info.add(surepassword);

    }

    /**
     * 验证码按钮状态改变60秒重新发送
     */
    private void changeYzmStatu() {
        forgetpasswordGetYzm.setEnabled(false);

        final Handler handlerTimeTask = new Handler();
        handlerTimeTask.postDelayed(new Runnable() {
            @Override
            public void run() {


                if (time <= 0) {
                    forgetpasswordGetYzm.setEnabled(true);
                    forgetpasswordGetYzm.setText("获取验证码");
                    forgetpasswordGetYzm.setTextColor(getResources().getColor(R.color.tab_choose));
                    time = 60;
                } else {
                    forgetpasswordGetYzm.setText(time + "秒后重新发送");
                    forgetpasswordGetYzm.setTextColor(getResources().getColor(R.color.gray66));
                    handlerTimeTask.postDelayed(this, 1000);
                }
                time--;
            }
        }, 1000);

    }

    /**
     * 获取验证码方法
     */
    private void getYzm() {
        Map<String, String> map = new HashMap<String, String>();
        get_info();
        map.put("tel", forgetpassword_info.get(0));
        map.put("type", "2");//1代表注册验证码
        map.put("code", HttpUtil.getParam());
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, Yzm.class, URLAddress.URLBASE + URLAddress.URL_YZM, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                Yzm str = (Yzm) response;

                if (str.getResult() == 1){
                    yzm_code = str.getData().getCode()+"";
                }else{
                    Toasts.show(ForgetPasswordActivity.this, ""+str.getErr_msg(), Toast.LENGTH_SHORT);
                }


              //  ArrayList list = (ArrayList) str.getData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                String e = error.toString();
            }
        });
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {

    }
}
